package com.group9.service;

import com.google.gson.Gson;
import com.group9.dto.Message;
import lombok.extern.slf4j.Slf4j;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by Lcouncillor on 2020/6/3.
 */
@Slf4j
@Component
@ServerEndpoint("/websocket/{userId}")
public class WebSocketServer {

    private static Logger log = Logger.getLogger(WebSocketServer.class);

    /**
     * 用于存放所有在线客户端
     */
    private static Map<String, Session> clients = new ConcurrentHashMap<>();

    private Gson gson = new Gson();

    @OnOpen
    public void onOpen(@PathParam("userId") String userId ,
                       Session session){
        log.info("有新的客户端上线: userId = "+ userId);
        clients.put(userId,session);
        log.info("当前连接数 = " + clients.size());

    }

    @OnClose
    public void onClose(@PathParam("userId") String userId,
                        Session session) {
        log.info("有客户端离线: : userId = " + userId);
        clients.remove(userId);
        log.info("当前连接数 = " + clients.size());
    }


    @OnError
    public void onError(@PathParam("userId") String userId,
                        Throwable throwable,
                        Session session) {
        log.info("[WebSocketServer] Connection Exception : userId = "+ userId + " , throwable = " + throwable.getMessage());
        clients.remove(userId);
        log.info("当前连接数 = " + clients.size());
    }


    @OnMessage
    public void onMessage(@PathParam("userId") String userId,
                            String message) {
        log.info("收到客户端发来的消息: userId = "+ userId + " , message = " + message);
        log.info(gson.fromJson(message, Message.class));
        if (message.equals("&")){

        }else{
//            WebSocketUtils.receive(userId , message);
//            return "Got your message ("+ message +").";
            this.sendTo(gson.fromJson(message, Message.class));
        }
    }

    /**
     * 发送消息
     *
     * @param message 消息对象
     */
    private void sendTo(Message message) {
        Session s = clients.get(message.getUserId());
//        System.out.println(clients.toString());

        if (s != null) {
            try {
                s.getBasicRemote().sendText(message.getMessage());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


}
